/**
 * edatagrid - jQuery EasyUI
 * 
 * Licensed under the GPL:
 *   http://www.gnu.org/licenses/gpl.txt
 *
 * Copyright 2011 stworthy [ stworthy@gmail.com ] 
 * 
 * Dependencies:
 *   datagrid
 *   messager
 * 
 */
(function($){
	function buildGrid(target){
		var opts = $.data(target, 'edatagrid').options;
		if(opts.tree){
			$(target).treegrid($.extend({}, opts, {
				singleSelect:false,
				onClickCell:function(field,data){
					if (opts.editing || (opts.editRowMap && opts.editRowMap[data.autoCode])){
						$(this).edatagrid('editCol',{"index":data.autoCode,"field":field});
						$(this).focusEditor(field);
					}
				},
				onBeforeLoad :function(rowData,param){
					$(this).removeData("deleteData");
					if (opts.onBeforeLoad) return opts.onBeforeLoad.call(target,rowData,param);
				}
					}));
		}else{
			var targetid = $(target).attr('id');
			//根据cookie中保存的列宽，修改opts
			if(opts.url) {
				var urlid = opts.url.substring(opts.url.indexOf("entityName=")+11, opts.url.length);
				var myindex = urlid.indexOf("&")===-1?urlid.length:urlid.indexOf("&");
				urlid = urlid.substring(0, myindex);
				urlid = urlid.replace(/[.]/g,"_");//当前data页的标识
				var acookie = readCookie('_colwidth_' + urlid);
				//如果cookie中存在列宽的设置，则对列宽重新赋值
				if(acookie) {
					var values = JSON.parse(acookie);
					var opt = opts.columns[0];
					var frozenOpt = opts.frozenColumns[0];
					//非固定列保存列宽设置
					for(var i in values) {
						if(values[i].width != null) {
							for(var j in opt) {
								if(values[i].field === opt[j].field) {
									opt[j].width = values[i].width;
									break;
								}
							}
						}
					}
					//固定列保存列宽设置
					for(var i in values) {
						if(values[i].width != null) {
							for(var j in frozenOpt) {
								if(values[i].field == frozenOpt[j].field) {
									frozenOpt[j].width = values[i].width;
									break;
								}
							}
						}
					}
				}
			} else {
				//如果没有url说明是新增表，以baseURI与id拼接出唯一键，在cookie中记录列宽
				var urlid = target.baseURI.substring(target.baseURI.indexOf("entityName=")+11, target.baseURI.length);
				var myindex = urlid.indexOf("&")===-1?urlid.length:urlid.indexOf("&");
				urlid = urlid.substring(0, myindex);
				urlid = urlid.replace(/[.]/g,"_");//当前data页的标识
				urlid = urlid + "_" + target.id;
				var acookie = readCookie('_colwidth_' + urlid);
				//如果cookie中存在列宽的设置，则对列宽重新赋值
				if(acookie) {
					var values = JSON.parse(acookie);
					var opt = opts.columns[0];
					var frozenOpt = opts.frozenColumns[0];
					for(var i in values) {
						if(values[i].width != null) {
							for(var j in opt) {
								if(values[i].field == opt[j].field) {
									opt[j].width = values[i].width;
									break;
								}
							}
						}
					}
					for(var i in values) {
						if(values[i].width != null) {
							for(var j in frozenOpt) {
								if(values[i].field == frozenOpt[j].field) {
									frozenOpt[j].width = values[i].width;
									break;
								}
							}
						}
					}
				}
			}
		$(target).datagrid($.extend({}, opts, {
			onLoadSuccess:function(data){
				/*为datagrid添加选择框被点击事件*/
				$(target).datagrid("getPanel").find("input[type='checkbox']").click(function(){
					/*如果shift被按住，进行多选操作，_shiftisdown是在body元素键盘事件中被定义的全局变量*/
					if(typeof _shiftisdown != "undefined" && _shiftisdown) {
						var onshiftisdownrownum = null;//shift选择前的选中行号
//						if(typeof _onshiftisdownrownum != "undefined" && _onshiftisdownrownum!=null) {
//							onshiftisdownrownum = _onshiftisdownrownum;
//						} else {
						/*判断是否有之前被选择的行，如果有获取最后一行的索引值*/
							var list = $(target).datagrid("getSelections");
							if(list.length > 0) {
								var last_index = null;
								for(var i=0; i<list.length; i++) {
									if(last_index !== null) {
										var new_index = $(target).datagrid("getRowIndex",list[i]);
										if(new_index > last_index) {
											last_index = new_index;
										}
									} else {
										last_index = $(target).datagrid("getRowIndex",list[i]);
									}
								}
								onshiftisdownrownum = last_index;
							}
//						}
						if(onshiftisdownrownum != null) {
							/*根据input元素父元素tr的datagrid-row-index获取被点击行的索引*/
							var index = parseInt($(this).parents("tr[datagrid-row-index]").attr("datagrid-row-index"));
							/*如果之前被选择的行索引在现在被选择的行索引之前，将两者之间的行进行选择*/
							if(onshiftisdownrownum < index) {
								for(var i=onshiftisdownrownum; i<index; i++) {
									$(target).datagrid("selectRow",i);
								}
							}
						}
					}
				});
				if (opts.onLoadSuccess) opts.onLoadSuccess.call(target, data);
			},
			//当发生拖动事件后，将对cookie进行修改
			onResizeColumn:function(field, width) {
				if(opts.url) {
					var urlid = opts.url.substring(opts.url.indexOf("entityName=")+11, opts.url.length);
					var myindex = urlid.indexOf("&")===-1?urlid.length:urlid.indexOf("&");
					urlid = urlid.substring(0, myindex);
					urlid = urlid.replace(/[.]/g,"_");//当前data页的标识
					var acookie = readCookie('_colwidth_' + urlid);
					if(acookie) {
						var values = JSON.parse(acookie);
						var mark = true;
						for(var i in values) {
							if(values[i].field == field) {
								values[i].width = width;
								mark = false;
								break;
							}
						}
						if(mark){
							values.push({"field":field,"width":width});
						}
						createCookie('_colwidth_' + urlid, JSON.stringify(values), 1000);
					} else {
						createCookie('_colwidth_' + urlid, '[{"field":"'+field+'","width":'+width+'}]', 1000);
					}
				} else {
					var urlid = target.baseURI.substring(target.baseURI.indexOf("entityName=")+11, target.baseURI.length);
					var myindex = urlid.indexOf("&")===-1?urlid.length:urlid.indexOf("&");
					urlid = urlid.substring(0, myindex);
					urlid = urlid.replace(/[.]/g,"_");//当前data页的标识
					urlid = urlid + "_" + target.id;
					var acookie = readCookie('_colwidth_' + urlid);
					if(acookie) {
						var values = JSON.parse(acookie);
						var mark = true;
						for(var i in values) {
							if(values[i].field == field) {
								values[i].width = width;
								mark = false;
								break;
							}
						}
						if(mark){
							values.push({"field":field,"width":width});
						}
						createCookie('_colwidth_' + urlid, JSON.stringify(values), 1000);
					} else {
						createCookie('_colwidth_' + urlid, '[{"field":"'+field+'","width":'+width+'}]', 1000);
					}
				}
			},
			onClickCell:function(index,field){
				if (opts.editing || (opts.editRowMap && opts.editRowMap[index.toString()])){
					//$(this).edatagrid('editRow', index);
					$(this).edatagrid('editCol',{"index":index,"field":field});
					$(this).focusEditor(field);
				}
			},
			onAfterEdit: function(index, row){
				opts.editIndex = undefined;
				var url = row.isNewRecord ? opts.saveUrl : opts.updateUrl;
				if (url){
					$.post(url, row, function(data){
						data.isNewRecord = null;
						$(target).datagrid('updateRow', {
							index: index,
							row: data
						});
						if (opts.tree){
							var t = $(opts.tree);
							var node = t.tree('find', row.id);
							if (node){
								node.text = row[opts.treeTextField];
								t.tree('update', node);
							} else {
								var pnode = t.tree('find', row[opts.treeParentField]);
								t.tree('append', {
									parent: (pnode ? pnode.target : null),
									data: [{id:row.id,text:row[opts.treeTextField]}]
								});
							}
						}
						opts.onSave.call(target, index, row);
					},'json');
				}
				if (opts.onAfterEdit) opts.onAfterEdit.call(target, index, row);
			},
			onCancelEdit: function(index, row){
				opts.editIndex = undefined;
				// by GaoXJ 2012-06-03
				/*if (row.isNewRecord) {
					$(this).datagrid('deleteRow', index);
				}*/
				if (opts.onCancelEdit) opts.onCancelEdit.call(target, index, row);
			},
			onBeforeLoad: function(param) {
				//$(this).datagrid('rejectChanges');
				$(this).edatagrid('clearColumnFilter');//清除过滤数据字段缓存
				if (opts.tree){
					var node = $(opts.tree).tree('getSelected');
					param[opts.treeParentField] = node ? node.id : undefined;
				}
				if (opts.onBeforeLoad) opts.onBeforeLoad.call(target, param);
			},
			onSelect : function(rowIndex, rowData) {
				if($(target).data("copyToClipboardType") == "col") {
					$(target).datagrid("getPanel").panel("panel").find("td").removeClass("datagrid-row-selected");
					var allColumnFields = $(target).datagrid('getColumnFields',true).concat($(target).datagrid('getColumnFields'));
					for(var i in allColumnFields) {
						var field = allColumnFields[i];
						var menuName = '#_dg_' + $(this).attr("id") + '_tmenu_' + field;
						if($(menuName).length) {
							var __target;
							$(menuName).children().each(function() {
								if($(this).find("span").attr("isSelCol")) {
									__target = $(this);
								}
							});
							$(menuName).menu('setIcon', {
								target: __target,
								iconCls: 'tree-checkbox0'
							});
						}
					}
				}
				$(target).data("copyToClipboardType", "row");
			},
			onHeaderContextMenu: function(e, field) {
				//console.log(field);
				var fldOpt = $(this).datagrid("getColumnOption", field);
				$(target).data("columnField", field); // 添加右键所在列的标识到datagrid
				if(fldOpt) {
					e.preventDefault();
					if(fldOpt.isFilterData) {//创建过滤菜单
						//获取or设置原始rows
						var rows = $(this).data("baseRows");
						if (!rows || rows.length == 0) {
							rows = $(this).datagrid("getRows");
							$(this).data("baseRows", rows);
						}
						if(rows.length) {
							var values = {},currentValues = {};
							//获取当前右击列所在数据，组装成一个以列值为键的对象
							$.each(rows,
							function(i, v) {
								if(v[field]!==undefined && v[field]!==null && v[field]!=="") {
									if(fldOpt.formatter) {
										values[v[field]] = fldOpt.formatter(v[field], v, i);
									} else {
										values[v[field]] = v[field].toString();
									}
								} else {
									values[""] = "空白";
								}
							});
							//创建右键列菜单
							var dgTarget = $(this);
							var menuName = '#_dg_' + $(this).attr("id") + '_tmenu_' + field;
							if ($(menuName).length == 0) {
								createColumnMenu(field, values, dgTarget, true);
//								console.log(field);
//								console.log(values);
//								console.log(dgTarget);
							}
							//获取当前过滤之后该列存在的数据
							var currentRows = $(this).datagrid("getRows");
							$.each(currentRows,
							function(i, v) {
								if(v[field]!==undefined && v[field]!==null && v[field]!=="") {
									if(fldOpt.formatter) {
										currentValues[v[field]] = fldOpt.formatter(v[field], v, i);
									} else {
										currentValues[v[field]] = v[field].toString();
									}
								} else {
									currentValues[""] = "空白";
								}
							});
							//判断已有列菜单中是否存在已经过滤的数据
							var m = $(menuName);
							
							//console.log(m);
							$.each(values,
							function(k, v) {
								var item = m.menu('findItem', v);
								if(item) {
									if (!currentValues[k]) { //不存在就设置当前的icon为未选中状态
										m.menu('setIcon', {
											target: item.target,
											iconCls: 'tree-checkbox0'
										});
										dgTarget.data("distic")[field][k] = v; //在当前列的过滤记录中记录当前已经过滤的数据名称
									} else if (dgTarget.data("distic")[field][k]) { //存在就设置当前的icon为选中状态
										m.menu('setIcon', {
											target: item.target,
											iconCls: 'tree-checkbox1'
										});
										delete dgTarget.data("distic")[field][k]; //在当前列的过滤记录中删除当前已经过滤的数据名称
									}
								}
							});
							var icon = 'tree-checkbox0';//未选中
							if ($.isEmptyObject(dgTarget.data("distic")[field])) { //判断当前列是否全部选中
								icon = 'tree-checkbox1';
							}
							var item = m.menu('findItem', "全选");
							m.menu('setIcon', {
								target: item.target,
								iconCls: icon
							});
							//显示列选择数据菜单
							//console.log(m);
							m.menu('show', {
								left: e.pageX,
								top: e.pageY
							});
						}
					} else {//创建选中单列和复制列菜单
						var dgTarget = $(this);
						var menuName = '#_dg_' + $(this).attr("id") + '_tmenu_' + field;
						if ($(menuName).length == 0) {
							createColumnMenu(field, values, dgTarget, false);
						}
						$(menuName).menu('show', {
							left: e.pageX,
							top: e.pageY
						});
					}
				}
				if(opts.onHeaderContextMenu) opts.onHeaderContextMenu.call(target,e,field);
			}
		}));
		//添加shift事件
		$("body").keydown(function(event){
			  switch(event.keyCode) {
			  case 16:_shiftisdown=true;//是否按住shift
			  }
		 }).keyup(function(event){
			  switch(event.keyCode) {
			  case 16:_shiftisdown=false;
//			  				_onshiftisdownrownum=null;//shift选择前的选中行号
			  }
		 });
//		var a = [1,2,3];
//		a.push("c");
//		createCookie('_dg_' + $(target).attr("id"),a,365);
//		console.log(readCookie('_dg_' + $(target).attr("id")));
		//读cookie是否有当前data的设置
//		var acookie = readCookie('_dg_' + $(target).attr("id"));
//		if(acookie != ""){
			//将cookie转成数组
//			while(acookie.length!=0){
//		 		var end = acookie.indexOf(",",0);
//		 		if(end!=-1){
//		 			console.log(acookie.substring(0,end));
//		 			var x = JSON.parse(acookie.substring(0,end));
//		 			if(x.hidden){
//		 				$(target).edatagrid('hideColumn',x.field);
//		 			}
//		 			acookie = acookie.substring(end+1,acookie.length);
//		 		}
//		 		else{
//		 			console.log(acookie);
//		 			var x = JSON.parse(acookie);
//		 			if(x.hidden){
//		 				$(target).edatagrid('hideColumn',x.field);
//		 			}
//		 			acookie = "";
//		 		}
//			}
			
			//var xx = JSON.parse(readCookie('_dg_' + $(target).attr("id")));
			//console.log(xx[0]);
			//根据cookie中的设置去控制咧的显隐
			
//		}
		
		//$.cookie('_dg_' + $(target).attr("id"));
		//console.log($.cookie('_dg_' + $(target).attr("id")));
		//$(target).edatagrid('hideColumn','ck');
		
	}
		if(opts.url) {
			var urlid = opts.url.substring(opts.url.indexOf("entityName=")+11, opts.url.length);
			var myindex = urlid.indexOf("&")===-1?urlid.length:urlid.indexOf("&");
			urlid = urlid.substring(0, myindex);
			urlid = urlid.replace(/[.]/g,"_");//当前data页的标识
			var acookie = readCookie('_dg_' + urlid);
			//console.log(acookie);
	//		console.log(JSON.parse(acookie));
			if(acookie) {
				//将cookie转成数组,根据cookie中的设置去控制咧的显隐
				var values = JSON.parse(acookie);
				var ColumnFields = $(target).edatagrid('getColumnFields',true).concat($(target).edatagrid('getColumnFields'));
				for(var i in values){
					if(values[i].hidden){
						var _field = values[i].field;
						//如果字段没有在设计器中被删，使用datagrid方法隐藏该字段
						for (var i in ColumnFields) {
							if(ColumnFields[i]==_field){
								$(target).datagrid('hideColumn',_field);
								$(target).datagrid('resize');
								break;
							}
						}
					}
				}
			}
			//右键设置列显示
			$(target).edatagrid('getPanel').panel('panel').find("div.datagrid-header-rownumber").parent("td").bind("contextmenu",function(e){
				//e.preventDefault();
				//if(e.which==3) // 1 = 鼠标左键 left; 2 = 鼠标中键; 3 = 鼠标右键 
				//{
					var values = [];//与cookie中的数组相同
					var menuName = '#_dg_' + $(target).attr("id") + '_tmenu_' + urlid;
					//如果没有menu，就创建一个新的
					if ($(menuName).length == 0) {
						var acookie = readCookie('_dg_' + urlid);
						$(target).edatagrid('getColumnFields');
						//拼接固定字段与非固定字段
						var ColumnFields = $(target).edatagrid('getColumnFields',true).concat($(target).edatagrid('getColumnFields'));
						for (var i in ColumnFields) {
							var a = $(target).edatagrid('getColumnOption',ColumnFields[i]);
							//创建一个记录设置的数组
							var value = {field:ColumnFields[i],hidden:false};
							if(a.title) {
								values.push(value);
							}
						}
						if(acookie) {
							//将cookie转成数组,根据cookie中的设置去控制咧的显隐
							var values_ = JSON.parse(acookie);
							for(var i in values_) {
								for(var j in values) {
									if(values[j].field === values_[i].field) {
										values[j].hidden = values_[i].hidden;
									}
								}
							}
						}
						//如果没有 menuName的Menu就创建一个
						//改为根据页面高度，动态设定列显隐控制菜单的高度
						createColScreenMenu(values, $(target), e, urlid);
					}
					$(menuName).menu('show', {
						left: e.pageX,
						top: e.pageY
					});
					//e.preventDefault();
					//e.stopPropagation();
					return false;
				//}
			});
		}
		
		/**
		* 创建列数据菜单
		* @param values 列属性数组
		* @param target 目标datagrid
		**/
		function createColScreenMenu(values, target, e, urlid) {
			var dgId = target.attr("id");
			var menuName = '_dg_' + dgId + '_tmenu_' + urlid;
			var height = $(window).height() - e.pageY - 50;
			var tmenu;
			if(values.length*22>height) {
				tmenu = $('<div id="' + menuName + '" class="easyui-menu easyui-panel _dg_tmenu_' + dgId + '" style="width:250px;height:' + height + 'px"></div>').appendTo('body');
			}else{
				tmenu = $('<div id="' + menuName + '" class="easyui-menu easyui-panel _dg_tmenu_' + dgId + '" style="width:250px"></div>').appendTo('body');
			}
			$('<div iconCls="tree-checkbox1"/>').html("<span isSelAll='true'>全选</span>").appendTo(tmenu);
			$('<div class="menu-sep"/>').appendTo(tmenu);
			for(var i in values) {
				var x = target.edatagrid('getColumnOption',values[i].field);
				var iconCls;
				if(values[i].hidden){
					iconCls = "tree-checkbox0";
				}else{
					iconCls = "tree-checkbox1";
				}
				var sp = "<span keyVal='" + values[i].field + "'>" + x.title + "</span>";
				$('<div iconCls="'+iconCls+'"/>').html(sp).appendTo(tmenu);
			}
			//实例化数据列选择菜单
			//menu显示滚动条，修改滚动条无法拖动。
			var scrollbarisonmousedown = false;
			tmenu.mousedown(function(){
				scrollbarisonmousedown = true;
			});
			tmenu.panel({});
			tmenu.menu({
				onHide : function() {
					if(scrollbarisonmousedown) {
						tmenu.menu('show');
					}
					scrollbarisonmousedown = false;
				},
				onClick: function(item) {
					var spObj = $(item.target).find("span");
					var itemVal = spObj.attr("keyVal");
					var isSelAll = false;
					if(spObj.attr("isSelAll")) {
						isSelAll = true;
					}
					if (isSelAll) {//全选
						if(item.iconCls == 'tree-checkbox0') { //全选
							var items = $(item.target).nextAll(".menu-item");
							$.each(items,
							function(k, v) {
								var disticItem = tmenu.menu('findItem', v);
								tmenu.menu('setIcon', {
									target: v,
									iconCls: 'tree-checkbox1'
								});
							});
							tmenu.menu('setIcon', {
								target: item.target,
								iconCls: 'tree-checkbox1'
							});
							//将所有列显示
							for(i in values){
								values[i].hidden = false;
								$(target).edatagrid('showColumn',values[i].field);
							}
						} else if(item.iconCls == 'tree-checkbox1'){ //全不选
							var items = $(item.target).nextAll(".menu-item");
							$.each(items, function(k,v) {
								var sp = $(v).find("span");
								var iv = sp.attr("keyVal");
								var itemName = sp.text();
								tmenu.menu('setIcon', {
									target: v,
									iconCls: 'tree-checkbox0'
								});
							});
							tmenu.menu('setIcon', {
								target: item.target,
								iconCls: 'tree-checkbox0'
							});
							//将所有列隐藏
							for(i in values){
								values[i].hidden = true;
								$(target).edatagrid('hideColumn',values[i].field);
								$(target).edatagrid('resize');
							}
						}
					} else if (!isSelAll && item.iconCls == 'tree-checkbox1') {
						//选中状态去除，即过滤
						tmenu.menu('setIcon', {
							target: item.target,
							iconCls: 'tree-checkbox0'
						});
						//隐藏一列
						for(i in values){
							if(values[i].field==itemVal){
								values[i].hidden = true;
								break;
							}
						}
						$(target).edatagrid('hideColumn',itemVal);
						$(target).edatagrid('resize');
					} else if (!isSelAll) {//取消过滤
						tmenu.menu('setIcon', {
							target: item.target,
							iconCls: 'tree-checkbox1'
						});
						//显示一列
						for(i in values){
							if(values[i].field==itemVal){
								values[i].hidden = false;
								break;
							}
						}
						$(target).edatagrid('showColumn',itemVal);
					}
					//刷新menu
					tmenu.menu('show');
					//$(target).edatagrid('fitColumns');
					$(target).edatagrid('fixColumnSize');
					var valuesstr = JSON.stringify(values);
					//console.log(valuesstr);
					createCookie('_dg_' + urlid,valuesstr,1000);
				}
			});
		}
		
		/*复制datagrid行或列数据到剪贴板，返回Excel格式数据*/
		function doCopyToClipboard() {
			var __panel = $(target).datagrid("getPanel").panel("panel");
			var length = $(target).datagrid('getRows').length;
			var rows = [];
			if($(target).data("copyToClipboardType") == "row") {
				for(var i=0; i<length; i++) {
					var __tr = __panel.find("tr.datagrid-row-selected[datagrid-row-index="+i+"]");
					if(__tr.length) {
						var row = [];
						__tr.each(function(i) {
							$(this).find("td:visible div:not(.datagrid-cell-rownumber)").each(function() {
								if($(this).children().length === 0) {
									row.push($(this).text());
								}
							});
						});
						rows.push(row);
					}
				}
			} else if($(target).data("copyToClipboardType") == "col") {
				for(var i=0; i<length; i++) {
					var __tr = __panel.find("tr[datagrid-row-index="+i+"]");
					if(__tr.length) {
						var row = [];
						__tr.each(function(i) {
							$(this).find("td.datagrid-row-selected:visible div:not(.datagrid-cell-rownumber)").each(function() {
								if($(this).children().length === 0) {
									row.push($(this).text());
								}
							});
						});
						rows.push(row);
					}
				}
			}
			var rowsdata = [];
			if(rows && rows.length) {
				for(var i in rows) {
					rowsdata.push(rows[i].join("\t"));
				}
			}
			return rowsdata.join("\r\n");
		}
		
		/*选中将复制到剪贴板的列*/
		function selectColumnToClipboard() {
			if($(target).data("copyToClipboardType")=="row") {
				$(target).datagrid("unselectAll");
			}
			$(target).data("copyToClipboardType","col");
			var field = $(target).data("columnField");
			$(target).datagrid("getPanel").panel("panel").find("td[field=" + field + "]").addClass("datagrid-row-selected");
		}
		
		/*取消选中将复制到剪贴板的列*/
		function unSelectColumnToClipboard() {
			var field = $(target).data("columnField");
			$(target).datagrid("getPanel").panel("panel").find("td[field=" + field + "]").removeClass("datagrid-row-selected");
		}
		
		/**
		* 创建列数据菜单
		* @param field 当前列
		* @param values 当期列组成的以数据为键的对象
		* @param target 目标datagrid
		* @param isFilter 显示过滤列
		**/
		function createColumnMenu(field, values, target, isFilter) {
			var dgId = target.attr("id");
			var menuName = '_dg_' + dgId + '_tmenu_' + field;
			var tmenu = $('<div id="' + menuName + '" class="_dg_tmenu_' + dgId + '" style="width:250px;"></div>').appendTo('body');
			$('<div iconCls="tree-checkbox0"/>').html("<span isNotFilter='true' isSelCol='true'>选中列</span>").appendTo(tmenu);
			$('<div iconCls="icon-copy" title="复制选中的行或列(请双击复制)"/>').html("<span isNotFilter='true' isCopy='true'>复制选中的行或列(请双击复制)</span>").appendTo(tmenu);
			if(dgId!="queryList" && opts.editing) {
				$('<div iconCls="icon-paste" title="粘帖列"/>').html("<span isNotFilter='true' isPaste='true'>粘帖列</span>").appendTo(tmenu);
			}	
			if(isFilter) {
				$('<div class="menu-sep"/>').appendTo(tmenu);
				$('<div iconCls="tree-checkbox1"/>').html("<span isSelAll='true'>全选</span>").appendTo(tmenu);
				$('<div class="menu-sep"/>').appendTo(tmenu);
				$.each(values,
				function(key, value) {
					var sp = "<span keyVal='" + key + "'>" + value + "</span>";
					$('<div iconCls="tree-checkbox1"/>').html(sp).appendTo(tmenu);
				});
				var disObj = target.data("distic");//初始化，已过滤数据存储对象
				if(disObj) {
					disObj[field] = {};
				} else {
					var obj = {};
					obj[field] = {};
					target.data("distic", obj);
				}
				//tmenu.data("distic", {});
			}
			//实例化数据列选择菜单
			tmenu.menu({
				onShow : function() {
					var menuObj = this;
					var obj = $("div[iconCls='icon-copy']", menuObj);//div[iconCls='icon-paste']
					//client.clip($("#bt_cancelSelfApprove"));
					var _zcClient_ = new ZeroClipboard(obj[0]);
					_zcClient_.on('ready', function(event) {
				        //console.log( 'movie is loaded' );
				        /*_zcClient_.on( 'beforecopy', function(event) {
					      console.log("1111");
					    });*/
				        
				        _zcClient_.on('copy', function(event) {
				        	var data = doCopyToClipboard();
					        event.clipboardData.setData('text/plain', data); 
					        //console.log("111");
				        });

				        _zcClient_.on('aftercopy', function(event) {
				          //console.log('Copied text to clipboard: ' + event.data['text/plain']);
				          alert("已复制到剪切板！");
				          ZeroClipboard.destroy();
				        });
				    });
					_zcClient_.on('error', function(e) {
						console.log("error:");
				        console.log(e);
				    });
				},
				onClick: function(item) {
					var spObj = $(item.target).find("span");
					var itemVal = spObj.attr("keyVal");
					if(spObj.attr("isNotFilter")) {
						//选中列或复制列
						if(spObj.attr("isSelCol")) {//选中列事件
							if(item.iconCls == 'tree-checkbox0') {
								//TODO 选中列，下面添加选中方法
								selectColumnToClipboard();
								tmenu.menu('setIcon', {
									target: item.target,
									iconCls: 'tree-checkbox1'
								});
							} else if(item.iconCls == 'tree-checkbox1') {
								//TODO 取消选中列，下面添加取消选中方法
								unSelectColumnToClipboard();
								tmenu.menu('setIcon', {
									target: item.target,
									iconCls: 'tree-checkbox0'
								});
							}
						}
						/*if(spObj.attr("isCopy")) {//复制列
							
						}*/
						if(spObj.attr("isPaste")) {//粘帖列
							/*var gridPanel = target.edatagrid('getPanel').panel('panel');
							var gridBody = gridPanel.find("div.datagrid-body");
							var e = jQuery.Event("mousedown");
				            e.which=86,e.ctrlKey=true;
							gridBody.trigger(e);*/
							alert("请使用Ctrl+V粘贴数据！");
						}
					} else {//过滤字段
						var isSelAll = false;
						if(spObj.attr("isSelAll")) {
							isSelAll = true;
						}
						if (isSelAll) {//全选
							if(item.iconCls == 'tree-checkbox0') { //全选
								$.each(target.data("distic")[field],
								function(k, v) {
									var disticItem = tmenu.menu('findItem', v);
									tmenu.menu('setIcon', {
										target: disticItem.target,
										iconCls: 'tree-checkbox1'
									});
								});
								target.data("distic")[field] = {};
								tmenu.menu('setIcon', {
									target: item.target,
									iconCls: 'tree-checkbox1'
								});
								dataFilter(field, target);
							} else if(item.iconCls == 'tree-checkbox1'){ //全不选
								var items = $(item.target).nextAll(".menu-item");
								$.each(items, function(k,v) {
									var sp = $(v).find("span");
									var iv = sp.attr("keyVal");
									var itemName = sp.text();
									tmenu.menu('setIcon', {
										target: v,
										iconCls: 'tree-checkbox0'
									});
									target.data("distic")[field][iv] = itemName;
								});
								tmenu.menu('setIcon', {
									target: item.target,
									iconCls: 'tree-checkbox0'
								});
								dataFilter(field, target);
							}
						} else if (!isSelAll && item.iconCls == 'tree-checkbox1') {//选中状态去除，即过滤
							target.data("distic")[field][itemVal] = item.text;
							tmenu.menu('setIcon', {
								target: item.target,
								iconCls: 'tree-checkbox0'
							});
							dataFilter(field, target);
						} else if (!isSelAll) {//取消过滤
							delete target.data("distic")[field][itemVal];
							tmenu.menu('setIcon', {
								target: item.target,
								iconCls: 'tree-checkbox1'
							});
							dataFilter(field, target);
						}
						tmenu.menu('show');
					}
				}
			});
		}

		/**
		* 从原始rows中过滤数据
		* @param field 当前列
		* @param target 目标datagrid
		**/
		function dataFilter(field, target) {
			var newRows = target.data("baseRows");
			var temp = [];
			var disticValue = target.data('distic');
			var isEmptyObj = true;
			$.each(disticValue, function(k, v){
				isEmptyObj = isEmptyObj && $.isEmptyObject(v);
			});
			if (isEmptyObj) {
				temp = newRows;
			} else {
				$.each(newRows,
					function(k, v) {
						var isNotFilter = true;
						$.each(disticValue, function(fld, obj){
							isNotFilter = isNotFilter && !obj[v[fld]];
						});
						if(isNotFilter) {
							temp.push(v);
						}
				});
			}
			target.datagrid("loadData", temp);
		}

		
		function numbox(_a,_b){
			var _c=$.data(_a,"numberbox");
			var _d=_c.options;
			var _e=_c.field.val();
			_b=_d.parser.call(_a,_b);
			_d.value=_b;
			_c.field.val(_b);
			//$(_a).val(_d.formatter.call(_a,_b));
			if(_e!=_b){
				_d.onChange.call(_a,_b,_e);
			}									
			//$(_a).val(_d.formatter.call(_a,_e));	
		};
	
		/**
		 * 查找上一个或下一个可编辑单元格
		 */
		function findPreOrNextEditableField(td, isPrev) {
			var nextTd = null;
			if(isPrev) {
				nextTd = td.prev("td[field]");
				//从非固定列跨至固定列
				if(!nextTd.length) {
					var columnfields = $(target).datagrid("getColumnFields", true);
					var fields = $(target).datagrid("getColumnFields");
					if($.inArray(td.attr("field"), fields) >= 0 && columnfields.length) {
						for(var i=0; i<fields.length; i++) {
							var nfOpt = $(target).datagrid("getColumnOption", columnfields[columnfields.length-i-1]);
							if(nfOpt && !nfOpt.hidden && nfOpt.editor && nfOpt.editor.type && nfOpt.editor.options && !nfOpt.editor.options.readonly && !nfOpt.editor.options.disabled) {
								nextTd = {length:1,
									  attr:function(){return columnfields[columnfields.length-i-1];}
									  };
								return nextTd;
							}
						}
					}
				}
			} else {
				nextTd = td.next("td[field]");
				//从固定列跨至非固定列
				if(!nextTd.length) {
					var columnfields = $(target).datagrid("getColumnFields", true);
					var fields = $(target).datagrid("getColumnFields");
					if($.inArray(td.attr("field"), columnfields) >= 0 && fields.length) {
						for(var i=0; i<fields.length; i++) {
							var nfOpt = $(target).datagrid("getColumnOption", fields[i]);
							if(nfOpt && !nfOpt.hidden && nfOpt.editor && nfOpt.editor.type && nfOpt.editor.options && !nfOpt.editor.options.readonly && !nfOpt.editor.options.disabled) {
								nextTd = {length:1,
										  attr:function(){return fields[i];}
										  };
								return nextTd;
							}
						}
					}
				}
			}
			if(nextTd.length) {
				if(nextTd.is(":visible")) {
					var nextField = nextTd.attr("field");
					var nfOpt = $(target).datagrid("getColumnOption", nextField);
					if(nfOpt && nfOpt.editor) {
						var edtType = nfOpt.editor.type;
						var edtOpt = nfOpt.editor.options;
						if(edtType && edtOpt) {
							if(edtOpt.readonly || edtOpt.disabled) {
								return findPreOrNextEditableField(nextTd, isPrev);
							} else {
								return nextTd;
							}
						} else {
							return findPreOrNextEditableField(nextTd, isPrev);
						}
					} else {
						return findPreOrNextEditableField(nextTd, isPrev);
					}
				} else {
					return findPreOrNextEditableField(nextTd, isPrev);
				}
			} else {
				return nextTd;
			}
		};
		function keyCtr(){		
			var grid = $(target);
			var opts = $.data(target, 'edatagrid').options;
			grid.edatagrid('getPanel').panel('panel').unbind('keydown');
			grid.edatagrid('getPanel').panel('panel').bind('keydown', function (e){			
				e.Handled = true;
				if(opts.tree){				
					 switch (e.keyCode) {
						case 38: // up
							var td = $(e.target).closest("td[field]");
							var field = td.attr("field");
							var index = td.parent().attr(
									"node-id");
							var upIndex = "";
							var currentParent = grid.treegrid('getParent',index);
							if(currentParent){
								var childList =currentParent.children;
								for(var i=0;i<childList.length;i++){
									if(childList[i].autoCode==index){
										if(i-1>=0){
											upIndex = childList[i-1].autoCode;
										}else{
											upIndex = currentParent.autoCode;
										}
									}
								}
							}else{
								var roots =  grid.treegrid('getRoots',index);
								for(var j=0;j<roots.length;j++){
									if(roots[j].autoCode==index){
										if(j-1>=0){
											upIndex = roots[j-1].autoCode;
										}else{
											upIndex = roots[j].autoCode;
										}
									}
								}
							}
							if ($.data(e.target, "numberbox")) {
								numbox(e.target, $(e.target).val());
							}
							if (index && (opts.editing || (opts.editRowMap && opts.editRowMap[upIndex])) 
									&& grid.edatagrid('validateCol',(e.target))) {
								var opt = {
									"index" : upIndex,
									"field" : field
								};
								var editOpt = {
									"index" : index,
									"field" : field
								};
								grid.datagrid('newEndEdit', editOpt);
								grid.datagrid('newBeginEdit', opt);
								opts.editIndex = upIndex;
								opts.editCol = field;
								grid.focusEditor(field);
							}
							break;
						case 40: // down
							var td = $(e.target).closest("td[field]");
							var field = td.attr("field");
							var index = td.parent().attr("node-id");
							var downIndex = "";
							var currentChild = grid.treegrid('getChildren',index);
							var currentParent = grid.treegrid('getParent',index);
							if(currentChild && currentChild.length>0){
								downIndex = currentChild[0].autoCode;
							}else if(currentParent){
								var childList =currentParent.children;
								for(var i=0;i<childList.length;i++){
									if(childList[i].autoCode==index){
										if(i+1<childList.length){
											downIndex = childList[i+1].autoCode;
										}else{
											var pcode = index.substring(0,4);
											var roots =  grid.treegrid('getRoots',pcode);
											for(var j=0;j<roots.length;j++){
												if(roots[j].autoCode==pcode){
													if(j+1<roots.length){
														downIndex= roots[j+1].autoCode;
													}
												}
											}
										
										}
									}
								}
							}else if(currentChild && currentChild.length<=0){
								var roots =  grid.treegrid('getRoots',index);
								for(var j=0;j<roots.length;j++){
									if(roots[j].autoCode==index){
										if(j+1<roots.length){
											downIndex= roots[j+1].autoCode;
										}else{
											downIndex = roots[j].autoCode;
										}
									}
								}
							}
							if ($.data(e.target, "numberbox")) {
								numbox(e.target, $(e.target).val());
							}
							if ((opts.editing || (opts.editRowMap && opts.editRowMap[downIndex])) 
									&& grid.edatagrid('validateCol',(e.target))) {
								var opt = {
									"index" : downIndex,
									"field" : field
								};
								var editOpt = {
									"index" : index,
									"field" : field
								};
								grid.datagrid('newEndEdit', editOpt);
								grid.datagrid('newBeginEdit', opt);
								opts.editIndex = downIndex;
								opts.editCol = field;
								grid.focusEditor(field);

							}
							break;
						case 37: // left
							var td = $(e.target).closest("td[field]");
							var field = td.attr("field");
							var prevTd = findPreOrNextEditableField(td, true);
							var num = prevTd.length;
							var newField = prevTd.attr("field");
							var index = td.parent().attr("node-id");
							if (num != 0
									&& $(e.target).getSelectionStart() == 0
									&& grid.edatagrid('validateCol',
											(e.target))) {
								if ($.data(e.target, "numberbox")) {
									numbox(e.target, $(e.target).val());
								}
								var opt = {
									"index" : index,
									"field" : newField
								};
								var editOpt = {
									"index" : index,
									"field" : field
								};
								grid.datagrid('newEndEdit', editOpt);
								grid.datagrid('newBeginEdit', opt);
								opts.editIndex = index;
								opts.editCol = newField;
								grid.focusEditor(newField);

							}
							break;
						case 39: // right
							var td = $(e.target).closest("td[field]");
							var valLength = $(e.target).val().length;
							var field = td.attr("field");
							var nextTd = findPreOrNextEditableField(td);
							var num = nextTd.length;
							var newField = nextTd.attr("field");
							var index = td.parent().attr("node-id");
							if (num != 0
									&& $(e.target).getSelectionStart() == valLength
									&& grid.edatagrid('validateCol',
											(e.target))) {
								if ($.data(e.target, "numberbox")) {
									numbox(e.target, $(e.target).val());
								}
								var opt = {
									"index" : index,
									"field" : newField
								};
								var editOpt = {
									"index" : index,
									"field" : field
								};
								grid.datagrid('newEndEdit', editOpt);
								grid.datagrid('newBeginEdit', opt);
								opts.editIndex = index;
								opts.editCol = newField;
								grid.focusEditor(newField);
							}
							break;
						case 9: // Tab					
							if(e.ctrlKey){
								var td = $(e.target).closest("td[field]");
								var index = td.parent().attr("node-id");
								var rowData = grid.treegrid("find",index);
								grid.edatagrid("insertNewRow",rowData);
							}else{
							var td = $(e.target).closest("td[field]");
							var field = td.attr("field");
							var nextTd = findPreOrNextEditableField(td);
							var num = nextTd.length;
							var nextField = nextTd.attr("field");
							var index = td.parent().attr("node-id");
							
							var currentData = grid.treegrid("find",index);
							var pCode = currentData.autoParentCode;
							var lastCode = "";
							var childList = [];
							var roots = [];
							if(pCode){//判断是字节点还是父节点
								var currentParent = grid.treegrid('getParent',index);
								childList =currentParent.children;
								lastCode = childList[childList.length-1].autoCode;
							}else{
								 roots =  grid.treegrid('getRoots',index);
								lastCode = roots[roots.length-1].autoCode;
							}
							if ($.data(e.target, "numberbox")) {
								numbox(e.target, $(e.target).val());
							}
							if (num != 0&& grid.edatagrid('validateCol',(e.target))) {
								var opt = {
									"index" : index,
									"field" : nextField
								};
								var editOpt = {
									"index" : index,
									"field" : field
								};
								grid.datagrid('newEndEdit', editOpt);
								grid.datagrid('newBeginEdit', opt);
								opts.editIndex = index;
								opts.editCol = nextField;
								grid.focusEditor(nextField);
							}  else if (num == 0
									&& lastCode != index
									&& grid.edatagrid('validateCol',
											(e.target))) {
								var nextIndex = "";
								if(pCode){	
									for(var i=0;i<childList.length;i++){
										if(childList[i].autoCode==index){
											nextIndex = childList[i+1].autoCode;
											break;
										}
									}
								}else{
									for(var j=0;j<roots.length;j++){
										if(roots[j].autoCode==index){	
											nextIndex = roots[j+1].autoCode;
											break;
										}
									}
								}					
							
								if(opts.editing || (opts.editRowMap && opts.editRowMap[nextIndex])) {
									var firstField = opts.treeField;
									var opt = {
										"index" : nextIndex,
										"field" : firstField
									};
									var editOpt = {
										"index" : index,
										"field" : field
									};
									grid.datagrid('newEndEdit', editOpt);
									grid.datagrid('newBeginEdit', opt);
									opts.editIndex = nextIndex;
									opts.editCol = firstField;
									grid.focusEditor(firstField);
								}
							}else if (num == 0
									&& lastCode == index
									&& grid.edatagrid('validateCol',
											(e.target))) {
								if(opts.editing) { //编辑模式下
									if(pCode){								
										grid.edatagrid("insertNewRow",currentParent);
									}else{			
										grid.edatagrid("addRow");
									}
								}
							} 
						}
						return false;
						break;	
					case 13:
						if ($.data(e.target, "numberbox")) {
							numbox(e.target, $(e.target).val());
						}
						if(e.ctrlKey){
							var td = $(e.target).closest("td[field]");
							var index = td.parent().attr("node-id");
							var rowData = grid.treegrid("find",index);
							grid.edatagrid("insertNewRow",rowData);
						}else{
							if(opts.editing && grid.edatagrid('validateCol',
									(e.target))) {
								var td = $(e.target).closest("td[field]");
								var index = td.parent().attr("node-id");
								var currentData = grid.treegrid("find",index);
								var pCode = currentData.autoParentCode;
								if(pCode){								
									grid.edatagrid("insertNewRow",currentParent);
								}else{			
									grid.edatagrid("addRow");
								}
							}
						}
						break;
				}
			 }else{		
							switch (e.keyCode) {
								case 38: // up
									var td = $(e.target).closest("td[field]");
									var field = td.attr("field");
									var index = td.parent().attr(
											"datagrid-row-index");
									index = parseInt(index);
									// var selected =
									// grid.datagrid('getSelected');
									// var index = grid.datagrid('getRowIndex',
									// selected);
									// var field =
									// grid.datagrid('SelectField',index);
									// grid.datagrid('selectRow', index - 1);
									if ($.data(e.target, "numberbox")) {
										numbox(e.target, $(e.target).val());
									}
									if (index && index > 0 
											&& (opts.editing || (opts.editRowMap && opts.editRowMap[(index-1).toString()])) 
											&& grid.edatagrid('validateCol',
													(e.target))) {
										var opt = {
											"index" : index - 1,
											"field" : field
										};
										var editOpt = {
											"index" : index,
											"field" : field
										};
										grid.datagrid('newEndEdit', editOpt);
										grid.datagrid('newBeginEdit', opt);
										opts.editIndex = index - 1;
										opts.editCol = field;
										grid.focusEditor(field);
									}
									break;
								case 40: // down
									var td = $(e.target).closest("td[field]");
									var field = td.attr("field");
									var index = td.parent().attr(
											"datagrid-row-index");
									var rows = grid.datagrid('getRows');
									var maxIndex = rows.length - 1;
									index = parseInt(index);
									maxIndex = parseInt(maxIndex);
									if ($.data(e.target, "numberbox")) {
										numbox(e.target, $(e.target).val());
									}
									if (maxIndex > index
											&& (opts.editing || (opts.editRowMap && opts.editRowMap[(index+1).toString()]))
											&& grid.edatagrid('validateCol',
													(e.target))) {
										var opt = {
											"index" : index + 1,
											"field" : field
										};
										var editOpt = {
											"index" : index,
											"field" : field
										};
										grid.datagrid('newEndEdit', editOpt);
										grid.datagrid('newBeginEdit', opt);
										opts.editIndex = index + 1;
										opts.editCol = field;
										grid.focusEditor(field);
									} else if(maxIndex == index
											&& opts.editing
											&& grid.edatagrid('validateCol',
													(e.target))) { //最后一行，新增行
										grid.edatagrid('addRow');
									}
									break;
								case 37: // left
									var td = $(e.target).closest("td[field]");
									var field = td.attr("field");
									//var prevTd = td.prev("td[field]");
									var prevTd = findPreOrNextEditableField(td, true);
									var num = prevTd.length;
									var newField = prevTd.attr("field");
									var index = td.parent().attr(
											"datagrid-row-index");
									if (num != 0
											&& $(e.target).getSelectionStart() == 0
											&& grid.edatagrid('validateCol',
													(e.target))) {
										/*修复数字控件无法用键盘移动的问题*/
										if ($.data(e.target, "numberbox")) {
											numbox(e.target, $(e.target).val());
										}
										var opt = {
											"index" : index,
											"field" : newField
										};
										var editOpt = {
											"index" : index,
											"field" : field
										};
										grid.datagrid('newEndEdit', editOpt);
										grid.datagrid('newBeginEdit', opt);
										opts.editIndex = index;
										opts.editCol = newField;
										grid.focusEditor(newField);

									}
									break;
								case 39: // right
									var td = $(e.target).closest("td[field]");
									var valLength = $(e.target).val().length;
									var field = td.attr("field");
									//var nextTd = td.next("td[field]");
									var nextTd = findPreOrNextEditableField(td);
									var num = nextTd.length;
									var newField = nextTd.attr("field");
									var index = td.parent().attr(
											"datagrid-row-index");
									
									if (num != 0
											&& $(e.target).getSelectionStart() == valLength
											&& grid.edatagrid('validateCol',
													(e.target))) {
										/*修复数字控件无法用键盘移动的问题*/
										if ($.data(e.target, "numberbox")) {
											numbox(e.target, $(e.target).val());
										}
										var opt = {
											"index" : index,
											"field" : newField
										};
										var editOpt = {
											"index" : index,
											"field" : field
										};
										grid.datagrid('newEndEdit', editOpt);
										grid.datagrid('newBeginEdit', opt);
										opts.editIndex = index;
										opts.editCol = newField;
										grid.focusEditor(newField);
									}
									break;
								case 9: // tab键
									var td = $(e.target).closest("td[field]");
									var field = td.attr("field");
									//var nextTd = td.next("td[field]");
									var nextTd = findPreOrNextEditableField(td);
									var num = nextTd.length;
									var nextField = nextTd.attr("field");
									var rows = grid.datagrid('getRows');
									var maxIndex = rows.length - 1;
									var index = td.parent().attr(
											"datagrid-row-index");
									maxIndex = parseInt(maxIndex);
									index = parseInt(index);
									if ($.data(e.target, "numberbox")) {
										numbox(e.target, $(e.target).val());
									}
									if (num != 0
											&& grid.edatagrid('validateCol',
													(e.target))) {
										
										var opt = {
											"index" : index,
											"field" : nextField
										};
										var editOpt = {
											"index" : index,
											"field" : field
										};
										grid.datagrid('newEndEdit', editOpt);
										grid.datagrid('newBeginEdit', opt);
										opts.editIndex = index;
										opts.editCol = nextField;
										grid.focusEditor(nextField);
									} else if (num == 0
											&& maxIndex > index
											&& (opts.editing || (opts.editRowMap && opts.editRowMap[(index+1).toString()]))
											&& grid.edatagrid('validateCol',
													(e.target))) {
										
//										var firstTd = td.parent()
//												.children("td")[0];
//										var firstField = $(firstTd).attr(
//												"field");
										var columnfields = $(target).datagrid("getColumnFields", true);
										columnfields.length ? firstField = columnfields[1] : firstField = $(target).datagrid("getColumnFields")[0];
										var opt = {
											"index" : index + 1,
											"field" : firstField
										};
										var editOpt = {
											"index" : index,
											"field" : field
										};
										grid.datagrid('newEndEdit', editOpt);
										grid.datagrid('newBeginEdit', opt);
										opts.editIndex = index + 1;
										opts.editCol = firstField;
										grid.focusEditor(firstField);
									} else if (opts.editing && num == 0
											&& maxIndex == index
											&& grid.edatagrid('validateCol',
													(e.target))) {
										
										grid.edatagrid('addRow');
									}
									return false;
									break;
								case 13: //回车
									if ($.data(e.target, "numberbox")) {
										numbox(e.target, $(e.target).val());
									}
									if(opts.editing && grid.edatagrid('validateCol',
											(e.target))) {
										grid.edatagrid('addRow');
									}
									break;
							}
			 		}
			});
		}
		function pasteFromExcel() {
			var grid = $(target);
			var tableKey = grid.attr('id');
			var opts = $.data(target, 'edatagrid').options;
			var gridPanel = grid.edatagrid('getPanel').panel('panel');
			var gridBody = gridPanel.find("div.datagrid-body");
			//表格粘贴
			gridBody.on('paste', function (e){	
				if(opts.editing) {
					if($(e.target).hasClass("datagrid-editable-input")) {return true;}
			        var text;
			        var clp = (e.originalEvent || e).clipboardData;
			        if (clp === undefined || clp === null) {
			            text = window.clipboardData.getData("text") || ""; 
			        } else {
			            text = clp.getData('text/plain') || "";
			        }
			        if (text !== "" && text.indexOf("\r\n") >= 0) {
			        	e.preventDefault();
			        	//console.log(e);
			        	pasteTableFromClipboard(text, gridPanel);
		            	return false;
		            }
				}
			});
			//列粘贴
			var fieldHeader = gridPanel.find("div.datagrid-header td");
			fieldHeader.on('paste', function(e) {
				var fieldName = $(this).attr("field");
				if(opts.editing) {
			        var text;
			        var clp = (e.originalEvent || e).clipboardData;
			        if (clp === undefined || clp === null) {
			            text = window.clipboardData.getData("text") || ""; 
			        } else {
			            text = clp.getData('text/plain') || "";
			        }
			        if (text !== "" && text.indexOf("\r\n") >= 0) {
			        	e.preventDefault();
			        	//console.log(e);
			        	pasteColumnFromClipboard(text, fieldName);
		            	return false;
		            }
				}
			});
		}
		
		/*将剪贴板的内容复制到指定表格*/
		function pasteTableFromClipboard(text, gridPanel) {
			var arr = text.split("\r\n");
        	var len = arr.length;
        	if(len) {
        		var fieldCols = gridPanel.find(".datagrid-header td[field]:not[field!='ck']:visible");
        		var rowData = [];
        		for(var i=0;i<len-1;i++) {
        			var row = arr[i];
        			var cols = row.split(/\t/);
        			var rowObj = {};
        			for(var j=0,colLen=cols.length;j<colLen;j++) {
        				var col = cols[j];
        				var fieldCol = fieldCols.eq(j);
        				if(fieldCol && fieldCol.length) {
        					var fieldName = fieldCol.attr("field");
        					rowObj[fieldName] = col;
        				}
        			}
        			rowData.push(rowObj);
        		}
        		if(opts.tree) {
        			jwpf.setTreeTableData($(target).attr('id'), rowData, true, false);
        		} else {
        			jwpf.setTableData($(target).attr('id'), rowData, true, false);
        		}
        	}
		}
		
		/*将剪贴板的内容复制到指定列*/
		function pasteColumnFromClipboard(text, fieldName) {
			var arr = text.split("\r\n");
        	var len = arr.length;
        	if(len) {
        		var rowData = [];
        		for(var i=0;i<len-1;i++) {
        			var rowObj = {};
					rowObj[fieldName] = arr[i].split(/\t+/)[0];
        			rowData.push(rowObj);
        		}
        		if(opts.tree) {
        			jwpf.setTreeTableData($(target).attr('id'), rowData, true, false);
        		} else {
        			jwpf.setTableData($(target).attr('id'), rowData, true, false, true);
        		}
        	}
		}
		
		keyCtr();
		pasteFromExcel();
	}
	//判断是否空行
	function isEmptyRow(row) {
		   var flag=true;
		   $.each(row,function(k,v){
			   if(k!="isNewRecord" && k!="autoParentCode" && k!="autoCode" &&k!="_parentId"&& k!="state"){
				   //为空v=false
				   //不为空v=true
			      flag=flag&&!v;
			   }
		   });
		   return flag;
	};
	//判断是否默认行
	function isDefaultRow(row, defaultRow) {
		var obj = $.extend(true, {}, row);
		for(var o in defaultRow) {
			if(defaultRow[o] === obj[o]) {
				obj[o] = undefined;
			} else {
				return false;
			}
		}
		var result = $.extend(true, {}, obj);
		return isEmptyRow(result);
	};
	//edatagrid初始化
	$.fn.edatagrid = function(options, param){
		if (typeof options == 'string'){
			var method = $.fn.edatagrid.methods[options];
			if (method){
				return method(this, param);
			} else {
				var opt = $.data(this[0], "edatagrid");
				if(opt && opt.options && opt.options.tree) {
					return this.treegrid(options, param);
				} else {
					return this.datagrid(options, param);
				}
			}
		}
		
		options = options || {};
		return this.each(function(){
			var state = $.data(this, 'edatagrid');
			if (state){
				$.extend(state.options, options);
			} else {
				if(options.tree){
					state = $.data(this,"edatagrid",{
						options:$.extend({editing: true},$.fn.treegrid.defaults,$.fn.treegrid.parseOptions(this),options)
						});
					if(state.lines){
						$(this).addClass("tree-lines");
					}
				}else{
				$.data(this, 'edatagrid', {
					options: $.extend({}, $.fn.edatagrid.defaults, $.fn.edatagrid.parseOptions(this), options)
					});
				}
			}
			buildGrid(this);
		});
	};
	
	$.fn.edatagrid.parseOptions = function(target){
		return $.extend({}, $.fn.datagrid.parseOptions(target), {
		});
	};
	//edatagrid新增的方法
	$.fn.edatagrid.methods = {			
		options: function(jq){
			var opts = $.data(jq[0], 'edatagrid').options;
			return opts;
		},
		enableEditing: function(jq){
			return jq.each(function(){
				var opts = $.data(this, 'edatagrid').options;
				opts.editing = true;
				$(this).datagrid('getPanel').panel('panel').find("div.datagrid-toolbar a").linkbutton("enable");
			});
		},
		validateCol:function(jq,obj){//检验当前列		
			  	if($.data(obj,"validatebox")){		  		
            			return $(obj).validatebox('isValid');
            	}else{         	
            		return true;
            	} 
		},
		validateRows:function(jq,rowObj){//检验行
			var rowFields = jq.datagrid('getColumnFields');
			var flag = true;
			for( var i = 0; i <rowFields.length; i++){
				var field = rowFields[i];
				var opt = jq.datagrid('getColumnOption',field);
				if(opt.required){
					if(rowObj[field]!==undefined && rowObj[field]!==null && rowObj[field]!==""){
						flag = true;
					}else{					
						$.messager.alert('提示信息','['+opt.title+']为必输项，请填写','info');
						return false;
					}
				}
			}
			return flag;
		},
		disableEditing: function(jq){
			return jq.each(function(){
				var opts = $.data(this, 'edatagrid').options;
				opts.editing = false;
				$(this).datagrid('getPanel').panel('panel').find("div.datagrid-toolbar a:not(:has(span.enableInView))").linkbutton("disable");
			});
		},//开启单行可编辑
		enableEditRow:function(jq, indexOpt) {
			return jq.each(function(){
				var dg = $(this);
				var opts = $.data(this, 'edatagrid').options;
				if(!opts.editRowMap) {
					opts.editRowMap = {};
				} 
				opts.editRowMap[indexOpt.index.toString()] = true;//表示index所在行可编辑
				if(indexOpt.isAutoFocus!==false) { //自动聚焦
					dg.edatagrid("editCol", indexOpt);//字段可编辑
					dg.focusEditor(indexOpt.field);//字段聚焦
				}
			});
		},//关闭单行可编辑
		disableEditRow:function(jq, index) {
			return jq.each(function(){
				var dg = $(this);
				var opts = $.data(this, 'edatagrid').options;
				if(opts.editRowMap) {
					delete opts.editRowMap[index.toString()];
				}
			});
		},//检查是否可编辑行
		checkEditRow:function(jq, index) {
			var opts = $.data(jq[0], 'edatagrid').options;
			if(opts.editRowMap && opts.editRowMap[index.toString()]) {
				return true;
			} else {
				return false;
			}
		},//开启单行可编辑，根据属性查记录
		enableEditRowByAttr:function(jq, indexOpt) {
			return jq.each(function(){
				var dg = $(this);
				var opts = $.data(this, 'edatagrid').options;
				//if(indexOpt.attrKey) {
					var allRows = [];
					if (opts.tree) {
						allRows = dg.edatagrid('getAllNodes');
					}else{
						allRows = dg.edatagrid('getRows');
					}
					var selRows = [];
					for(var i=0,len=allRows.length;i<len;i++) {
						var row = allRows[i];
						if(indexOpt.attrKey) {
							if(row[indexOpt.attrKey] == indexOpt.attrVal) {
								if(opts.tree) {
									selRows.push(row.autoCode);
								} else {
									selRows.push(i);
								}
							}
						} else { //attrKey为空时，默认开启全部可编辑
								if(opts.tree) {
									selRows.push(row.autoCode);
								} else {
									selRows.push(i);
								}
						}
					}
					for(var i=0,len=selRows.length;i<len;i++) {
						indexOpt["index"] = selRows[i];
						if(i == 0) {
							indexOpt["isAutoFocus"] = (indexOpt["isAutoFocus"] && true);
						} else {
							indexOpt["isAutoFocus"] = false;
						}
						dg.edatagrid("enableEditRow", indexOpt);
					}
				//}
			});
		},
		editRow: function(jq, index){//编辑行
			return jq.each(function(){
				var dg = $(this);
				var opts = $.data(this, 'edatagrid').options;
				var editIndex = opts.editIndex;
				if (editIndex != index){
					if (dg.datagrid('validateRow', editIndex)){
						dg.datagrid('endEdit', editIndex);
						dg.datagrid('beginEdit', index);
						opts.editIndex = index;
					} else {
						setTimeout(function(){
							dg.datagrid('selectRow', editIndex);
						}, 0);
					}
				}
			});
		},
		editCol: function(jq,opt){//编辑单元格		
			var index = opt.index;
			var field = opt.field;
			return jq.each(function(){
			var dg = $(this);
			var opts = $.data(this, 'edatagrid').options;			
			var editIndex = opts.editIndex;
				if (editIndex != index || editCol!=field ){
					var tr=opts.finder.getTr(this,editIndex);				
					var td =tr.find("td[field="+opts.editCol+"]");
					var div = td.find("div.datagrid-editable");
					var input = div.find("input.validatebox-text");
				if(input && input.length>0){		
				if (dg.edatagrid('validateCol', input[0])){								
					var editCol =opts.editCol;									
					var editOpt={"index":editIndex,"field":editCol};		
					dg.datagrid('newEndEdit',editOpt);
					dg.datagrid('newBeginEdit',opt);
					opts.editIndex = index;
					opts.editCol = field;													
				} else {
					setTimeout(function(){
						dg.datagrid('selectRow', editIndex);
					}, 0);
				}
			}else{
				var editCol =opts.editCol;									
				var editOpt={"index":editIndex,"field":editCol};		
				dg.datagrid('newEndEdit',editOpt);
				dg.datagrid('newBeginEdit',opt);
				opts.editIndex = index;
				opts.editCol = field;	
			}
				}
				
		});
	  },
	  ChildTabs : function(jq){
			return jq.each(function(){
			var dg = $(this);		
			var opts = $.data(this, 'edatagrid').options;	
			var editIndex = opts.editIndex;
			var editCol =opts.editCol;
			if(editIndex && editCol){
				dg.edatagrid('editCol',{"index":editIndex,"field":editCol});
				dg.focusEditor(editCol);
			}else{
				dg.edatagrid('addRow');
			}
			});
		},
		addRow : function(jq, row) {//添加新行
			return jq
					.each(function() {
						var dg = $(this);
						var opts = $.data(this, 'edatagrid').options;
						if (opts.editIndex >= 0) {
							if (!dg.datagrid('validateRow', opts.editIndex)) {
								dg.datagrid('selectRow', opts.editIndex);
								return;
							}
							var editOpt = {
								"index" : opts.editIndex,
								"field" : opts.editCol
							};
							dg.datagrid('newEndEdit', editOpt);
						}
						var defaultRow = $.extend({}, opts.defaultRow);
						var aRow = {}; 
						if(opts.tree) {
							var newcode = "";
							if(row && row.autoParentCode) {
								var pCode = row.autoParentCode;
								var childList = dg.treegrid('getChildren', pCode);
								newcode = dg.createNewCode(pCode, childList);
							} else {
								var rootList = dg.treegrid('getRoots');
								newcode = dg.createNewCode("", rootList);
							}
							aRow = {
								"_parentId" : null,
								"autoCode" : newcode,
								"autoParentCode" : null,
								"isNewRecord" : true
							};
							aRow = $.extend({}, defaultRow, aRow);
							if(row) {
								aRow = $.extend({}, aRow, row);
							}
							aRow["_parentId"] = aRow["autoParentCode"];
							dg.treegrid('append', {
								parent: aRow["_parentId"],
								data : [aRow]
							});
							var field = opts.treeField;
							newcode = aRow["autoCode"];
							opts.editCol = field;
							opts.editIndex = newcode;
							var opt = {
								"index" : newcode,
								"field" : field
							};
							if(aRow["_isAutoFocus_"] !== false) {
								dg.datagrid('newBeginEdit', opt);
							}
							if (row != false && aRow["_isAutoFocus_"] !== false) {
								dg.focusEditor(field);
							}
						} else {
							aRow = {isNewRecord : true};
							aRow = $.extend({}, defaultRow, aRow);
							if(row) {
								aRow = $.extend({}, aRow, row);
							}
							dg.datagrid('appendRow', aRow);
							var rows = dg.datagrid('getRows');
							opts.editIndex = rows.length - 1;
							var tr = opts.finder.getTr(this, opts.editIndex);
							var tdList = tr.find("td[field]");
							for ( var i = 0; i < tdList.length; i++) {
								var div = $(tdList[i]).find(
										"div.datagrid-cell-check");
								if (div.length == 0) {
									opts.editCol = $(tdList[i]).attr("field");
									break;
								}
							}
							var field = opts.editCol;
							var opt = {
								"index" : opts.editIndex,
								"field" : field
							};
							if(aRow["_isAutoFocus_"] !== false) {
								dg.datagrid('newBeginEdit', opt);
							}
							if (row != false && aRow["_isAutoFocus_"] !== false) {
								dg.focusEditor(field);
							}
						}
						if(opts.onAdd)
							opts.onAdd.call(this, opts.editIndex,
								aRow);
					});
		},
		insertNewRow : function(jq, index) {//插入新行
			return jq.each(function() {
				var dg = $(this);
				var opts = $.data(this, 'edatagrid').options;
				var defaultRow = $.extend({}, opts.defaultRow);
				if (opts.tree) {
					var pCode = index.autoCode;
					var pLength = pCode.length;
					var newcode = "";
					var childList = dg.treegrid('getChildren', pCode);
					var newcode = dg.createNewCode(pCode, childList);
					var aRow = {
							"_parentId" : pCode,
							"autoCode" : newcode,
							"autoParentCode" : pCode,
							"isNewRecord" : true
					};
					aRow = $.extend({}, defaultRow, aRow);
					if(index.row) {
						aRow = $.extend({}, aRow, index.row);
					}
					aRow["_parentId"] = aRow["autoParentCode"];
					var newChildData = [aRow];
					dg.treegrid('append', {
						parent : pCode,
						data : newChildData
					});
					var field = opts.treeField;
					newcode = aRow["autoCode"];
					dg.edatagrid('editCol', {
						"index" : newcode,
						"field" : field
					});
					dg.focusEditor(field);
					if (opts.onAdd)
						opts.onAdd.call(this, newcode, aRow);
				} else {
					if (opts.editIndex >= 0) {
						if (!dg.datagrid('validateRow', opts.editIndex)) {
							dg.datagrid('selectRow', opts.editIndex);
							return;
						}
						var editOpt = {
							"index" : opts.editIndex,
							"field" : opts.editCol
						};
						dg.datagrid('newEndEdit', editOpt);
					}
					var rows = dg.datagrid('getRows');
					var aRow = {
							isNewRecord : true
					};
					aRow = $.extend({}, defaultRow, aRow);
					if (index >= 0 && index <= rows.length) {
						dg.datagrid('insertRow', {
							index : index,
							row : aRow
						});
						//rows = dg.datagrid('getRows');
						opts.editIndex = index;
					} else {
						dg.datagrid('appendRow', aRow);
						//rows = dg.datagrid('getRows');
						//opts.editIndex = rows.length - 1;
						opts.editIndex = rows.length;
					}
					var tr = opts.finder.getTr(this, opts.editIndex);
					var tdList = tr.find("td[field]");
					for ( var i = 0; i < tdList.length; i++) {
						var div = $(tdList[i]).find("div.datagrid-cell-check");
						if (div.length == 0) {
							opts.editCol = $(tdList[i]).attr("field");
							break;
						}
					}
					var field = opts.editCol;
					var opt = {
						"index" : opts.editIndex,
						"field" : field
					};
					dg.datagrid('newBeginEdit', opt);
					dg.focusEditor(field);
					if (opts.onAdd)
						opts.onAdd.call(this, opts.editIndex,
								aRow);
				}
			});
		},
		saveRow: function(jq){//保存edatagrid中的数据
				var opts = jq.edatagrid('options');
				var index = opts.editIndex;
				var field = opts.editCol;
				if((index ||index==0) && field) {
					var editOpt={"index":index,"field":field};
					jq.datagrid('newEndEdit', editOpt);
				}
				var defaultRow = opts.defaultRow || {};
				var allRows = [];
				if (opts.tree) {
					allRows = jq.edatagrid('getAllNodes');
				}else{
					allRows = jq.edatagrid('getRows');
				}
				var rows = [];
				for ( var k = 0,len=allRows.length; k < len; k++) {
					if($.isEmptyObject(defaultRow)){//默认值为空
						if(!isEmptyRow(allRows[k])){//判断空值行
							//校验
							if(jq.edatagrid('validateRows',allRows[k])){
								rows.push(allRows[k]);
							}else{
								return false;
							}
						}
					}else{
						if(!isDefaultRow(allRows[k], defaultRow)){//判断默认行
							//校验
							if(jq.edatagrid('validateRows',allRows[k])){
								rows.push(allRows[k]);
							}else{
								return false;
							}
						}
					}
				}				
				return rows;
		},//批量删除行
		deleteRows:function(jq, rows) {
			if(rows && rows.length) {
				var lastDeleteIndex = 0;
				for ( var i = rows.length-1; i >= 0; i--) {
					var row = rows[i];
					var index = jq.edatagrid('getRowIndex', row);
					jq.edatagrid("deleteRow", index);
					lastDeleteIndex = index;
				}
				if(lastDeleteIndex > 0) {
					var allRows = jq.edatagrid("getRows");
					for(var i=lastDeleteIndex,len=allRows.length;i<len;i++) {
						jq.edatagrid("refreshRow", i);
					}
				}
				var opts = jq.edatagrid('options');
				opts.editIndex = null;
				opts.editCol = null;
			}
		},
		validEmptyOrDefaultRow:function(jq, row) {
			var opts = jq.edatagrid('options');	
			var defaultRow = opts.defaultRow || {};
			if($.isEmptyObject(defaultRow)){
				return isEmptyRow(row);
			} else {
				return isDefaultRow(row, defaultRow);
			}
		},
		clearColumnFilter:function(jq) {
			return jq.each(function() {
				$(this).removeData("baseRows");
				$(this).removeData("distic");
				var dgId = $(this).attr("id");
				var menuClass = "div._dg_tmenu_" + dgId;
				$(menuClass).remove();
			});
		},
		getAllNodes: function(jq){
				var root = jq.treegrid('getRoots');
				var dataArr = [];
				jq.getTreeData(root,dataArr);
				return 	dataArr;
			
		},
		removeNodes :function(jq,nodeData){
			return jq.each(function(){
				var select = [];
		     	var delArr = $(this).data("deleteData");
		     	delArr = delArr||[];
		     	select.push(nodeData);
		     	var dataArr = [];
		     	$(this).getTreeData(select,dataArr);
		     	if(dataArr.length>0){
		     		for(var i = 0; i < dataArr.length; i++) {
		     			var id = dataArr[i].id;
		     			if(id){
		    				delArr.push(dataArr[i]);
		    			}
					}
				}
		     	$(this).data("deleteData",delArr);
		     	$(this).treegrid('remove',nodeData.autoCode);	
			});			
		},
		removeAllNodes:function(jq) {
			return jq.each(function(){
				var dg = $(this);
				var roots = dg.treegrid("getRoots");
				if(roots && roots.length) {
					for(var i=0,len=roots.length;i<len;i++) {
						dg.edatagrid("removeNodes", roots[i]);
					}
				}
			});
		},
		getDeleteNodes : function(jq){					
			return jq.data("deleteData");		
		},
		update:function(jq,data){//更新edatagrid
			return jq.each(function(){
			var tg = $(this);
			var opts = tg.edatagrid('options');
			var currentCode = data.id;
			var _dc={};
			 var node = tg.treegrid('find',currentCode);
			var pCode = node.autoParentCode;
			var nodesArr =[];
			if(pCode){
				 var p = tg.treegrid('getParent',currentCode);
				 nodesArr = p.children;
			}else{
				 nodesArr = tg.treegrid('getRoots');
			}
			for(var i=0;i<nodesArr.length;i++){
				if(nodesArr[i].autoCode==currentCode){
					if(data.update){//更新
					_dc = $.extend(nodesArr[i],data.row);
					}else{//替换
					_dc = data.row;	
					}					
					nodesArr[i] = _dc;
					break;
				}
			}		
			var _dd=tg.treegrid("getLevel",data.id)-1;
			var _de=opts.rowStyler?opts.rowStyler.call(this,_dc):"";
			function _df(_e0){
				var _e1=tg.treegrid("getColumnFields",_e0);
				var tr=opts.finder.getTr(this,data.id,"body",(_e0?1:2));
				var _e2=tr.find("div.datagrid-cell-rownumber").html();
				var _e3=tr.find("div.datagrid-cell-check input[type=checkbox]").is(":checked");
				tr.html(opts.view.renderRow(this,_e1,_e0,_dd,_dc));
				tr.attr("style",_de||"");
				tr.find("div.datagrid-cell-rownumber").html(_e2);
				if(_e3){
				tr.find("div.datagrid-cell-check input[type=checkbox]")._propAttr("checked",true);
				}
				};
				_df.call(this,true);
				_df.call(this,false);
				tg.treegrid("fixRowHeight",data.id);
			});		
		},
		cancelRow: function(jq){
			return jq.each(function(){
				var index = $(this).edatagrid('options').editIndex;
				$(this).datagrid('cancelEdit', index);
			});
		},
		destroyRow: function(jq){
			return jq.each(function(){
				var dg = $(this);
				var opts = $.data(this, 'edatagrid').options;
				var row = dg.datagrid('getSelected');
				if (!row){
					$.messager.show({
						title: opts.destroyMsg.norecord.title,
						msg: opts.destroyMsg.norecord.msg
					});
					return;
				}
				$.messager.confirm(opts.destroyMsg.confirm.title,opts.destroyMsg.confirm.msg,function(r){
					if (r){
						var index = dg.datagrid('getRowIndex', row);
						if (row.isNewRecord){
							dg.datagrid('cancelEdit', index);
							//add by GaoXJ 2012-06-03
							dg.datagrid('deleteRow', index);
						} else {
							if (opts.destroyUrl){
								$.post(opts.destroyUrl, {id:row.id}, function(){
									if (opts.tree){
										dg.datagrid('reload');
										var t = $(opts.tree);
										var node = t.tree('find', row.id);
										if (node){
											t.tree('remove', node.target);
										}
									} else {
										dg.datagrid('cancelEdit', index);
										dg.datagrid('deleteRow', index);
									}
									opts.onDestroy.call(dg[0], index, row);
								});
							} else {
								dg.datagrid('cancelEdit', index);
								dg.datagrid('deleteRow', index);
							}
						}
					}
				});
			});
		}
	};
	
	$.fn.edatagrid.defaults = $.extend({}, $.fn.datagrid.defaults, {
		editing: true,
		editIndex: -1,
		destroyMsg:{
			norecord:{
				title:'Warning',
				msg:'No record is selected.'
			},
			confirm:{
				title:'Confirm',
				msg:'Are you sure you want to delete?'
			}
		},
		destroyConfirmTitle: 'Confirm',
		destroyConfirmMsg: 'Are you sure you want to delete?',
		
		url: null,	// return the datagrid data
		saveUrl: null,	// return the added row
		updateUrl: null,	// return the updated row
		destroyUrl: null,	// return {success:true}
		
		tree: null,		// the tree selector
//		treeUrl: null,	// return tree data
//		treeDndUrl: null,	// to process the drag and drop operation, return {success:true}
//		treeTextField: 'name',
//		treeParentField: 'parentId',
		
		onAdd: function(index, row){},
		onSave: function(index, row){},
		onDestroy: function(index, row){}
	});
})(jQuery);


$.fn.setCursorPosition = function(position){
    if(this.lengh == 0)  return this;
    return $(this).setSelection(position, position);
};

$.fn.setSelection = function(selectionStart, selectionEnd) {
    if (this.lengh == 0)
		return this;
	input = this[0];
	if ($(input).is(":hidden")) {
		input = $(input).next().find("input:visible")[0];
	}
	if (input) {
		if (input.createTextRange) {
			var range = input.createTextRange();
			range.collapse(true);
			range.moveEnd('character', selectionEnd);
			range.moveStart('character', selectionStart);
			range.select();
		} else if (input.setSelectionRange) {
			input.focus();
			try {
				input.setSelectionRange(selectionStart, selectionEnd);
			} catch(e) {}
		}
	}
	return this;
};

$.fn.focusEnd = function(){	
	 if($(this).is(":hidden")){
			var value = $($(this).next().find("input:visible")[0]).val();	
			if(value!=null){
				var length = value.length;		
			    this.setCursorPosition(length);
			}
	    }else if(this.val()!=null){
	    	var length = this.val().length;		
	    	this.setCursorPosition(length);
	}
};

$.fn.focusEditor=function(field){//edatagrid聚焦方法
	var opts = $(this).edatagrid("options");
	var editor = $(this).edatagrid('getEditor', {index:opts.editIndex,field:field});	
	if (editor){	
			
		var _4a =$(editor.target);	
		if(_4a.hasClass("combo-f")){
			_4a.combo('showPanel');	
		}//else if(_4a.hasClass("Wdate")){					
			//_4a.trigger("click");
		//}	
		editor.target.focusEnd();
	} else {
		
		var editors = $(this).edatagrid('getEditors', opts.editIndex);
		if (editors.length){
			editors[0].target.focus();
		}
	}
};

/*
$.fn.getSelectionStart=function(){
	var o = $(this)[0];
    if (o.createTextRange) {
        var r = document.selection.createRange().duplicate();
        r.moveEnd('character', o.value.length);
        if (r.text == '') return o.value.length;
        return o.value.lastIndexOf(r.text);
    } else {
    	return o.selectionStart;
    }
};*/

$.fn.getSelectionStart = function(){
    if(this.lengh == 0) return -1;
    input = this[0];
    var pos = input.value.length;
    if (input.createTextRange) {
      var r = document.selection.createRange().duplicate();
      r.moveEnd('character', input.value.length);
      if (r.text == '') 
        pos = input.value.length;
      pos = input.value.lastIndexOf(r.text);
    } else if(typeof(input.selectionStart)!="undefined")
      pos = input.selectionStart;
    
    return pos;
  };
  
  $.fn.getSelectionEnd = function(){
    if(this.lengh == 0) return -1;
    input = this[0];
    var pos = input.value.length;
    if (input.createTextRange) {
      var r = document.selection.createRange().duplicate();
      r.moveStart('character', -input.value.length);
      if (r.text == '') 
        pos = input.value.length;
      pos = input.value.lastIndexOf(r.text);
    } else if(typeof(input.selectionEnd)!="undefined")
      pos = input.selectionEnd;
    
    return pos;
  };

  $.fn.getCursorPosition = function(){
    if(this.lengh == 0) return -1;
    return $(this).getSelectionStart();
  };
  $.fn.createNewCode = function(pCode,childList){
	  var maxVal = "";
	  if(childList && childList.length>0){
		var codeArr = [];
			for(var i=0;i<childList.length;i++){
				var ccode = childList[i].autoCode;
				var lastcode = ccode.substring(pCode.length,ccode.length);
				codeArr.push(parseInt(lastcode,10));
			}
			
			if(codeArr.length > 0) {
				var maxv = Math.max.apply(null, codeArr);				
				maxv = maxv+1;
				maxVal = maxv.toString();
				var len = 4-maxVal.length;
				for(var k = 0;k<len;k++){
					maxVal = "0"+maxVal;
				}
			}
	  }else{		 		  
		  maxVal = "0000";
	  }
			return pCode+maxVal;
		};
	$.fn.getTreeData = function(root,dataArr){
		for (var k = 0; k< root.length; k++) {
			if(root[k]) {
				dataArr.push(root[k]);
				var child = root[k].children;
				if(child && child.length>0){				
					$(this).getTreeData(child,dataArr);
				}
			}
		}
	};
  $.fn.getSelection = function(){
    if(this.lengh == 0) return -1;
    var s = $(this).getSelectionStart();
    var e = $(this).getSelectionEnd();
    return this[0].value.substring(s,e);
  };
  
  $.fn.pasteEvents = function( delay ) { 
	    if (delay == undefined) delay = 20; 
	    return $(this).each(function() { 
	        var $el = $(this); 
	        $el.on("paste", function() { 
	            $el.trigger("prepaste"); 
	            setTimeout(function() { $el.trigger("postpaste"); }, delay); 
	        }); 
	    }); 
	}; 